<template>
  <el-form class="login-form"
           status-icon
           :rules="loginRules"
           ref="loginForm"
           :model="loginForm"
           label-width="0">
    <el-form-item prop="username">
      <el-input size="small"
                @keyup.enter.native="handleLogin"
                v-model="loginForm.username"
                auto-complete="off"
                :placeholder="$t('login.username')">
        <i slot="prefix"
           class="icon-yonghu"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input size="small"
                @keyup.enter.native="handleLogin"
                :type="passwordType"
                v-model="loginForm.password"
                auto-complete="off"
                :placeholder="$t('login.password')">
        <i class="el-icon-view el-input__icon"
           slot="suffix"
           @click="showPassword"></i>
        <i slot="prefix"
           class="icon-mima"></i>
      </el-input>
    </el-form-item>
    <el-form-item v-if="captchaMode" prop="code">
      <el-row :span="24">
        <el-col :span="16">
          <el-input size="small"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.code"
                    auto-complete="off"
                    :placeholder="$t('login.code')">
            <i slot="prefix" class="icon-yanzhengma"/>
          </el-input>
        </el-col>
        <el-col :span="8">
          <div class="login-code">
            <img :src="loginForm.image" class="login-code-img" @click="refreshCode"
            />
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary"
                 size="small"
                 @click.native.prevent="handleLogin"
                 class="login-submit">{{$t('login.submit')}}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {mapGetters} from 'vuex';
import website from '@/config/website';
import {getCaptcha} from '@/api/user';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {querySysTenantUserSetting} from '@/api/system/sysUserSettingApi';
import {setStore, getStore,removeStore} from '@/util/store'
import {buryingPoint} from '@/util/buryingPoint'

export default {
  name: 'userlogin',
  data() {
    return {
      tenantId:'',
      tenantMode: website.tenantMode,
      captchaMode: website.captchaMode,
      loginForm: {
        //用户名
        username: '',
        //密码
        password: '',
        //账户类型
        type: '',
        //验证码的值
        code: '',
        //验证码的索引
        key: '',
        //预加载白色背景
        image: '',
      },
      loginRules: {
        tenantId: [
          {required: false, message: '请输入租户ID', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, message: '密码长度最少为6位', trigger: 'blur'}
        ]
      },
      passwordType: 'password',
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['userInfo','recordChanged','tagWel','website','timeOutFLag'])
  },
  created() {
    let urlParam = this.$toolUtil.UrlSearch();
    if(urlParam.tenantId){
      this.tenantId = urlParam.tenantId;
    }
    else{
      this.tenantId = this.website.defaultTenantId;
    }
    localStorage.setItem('tenantId', this.tenantId);
    //this.refreshCode();
  },
  mounted() {
    //如果登录用户存在，则设置
    if(this.$getStore({name:'loginUserName'})){
      this.loginForm.username = this.$getStore({name:'loginUserName'});
    }
  },
  props: [],
  methods: {
    refreshCode() {
      getCaptcha().then(res => {
        const data = res.data.data;
        this.loginForm.key = data.key;
        this.loginForm.image = data.image;
      })
    },
    showPassword() {
      this.passwordType === ''
        ? (this.passwordType = 'password')
        : (this.passwordType = '');
    },
    handleLogin() {
      this.$store.dispatch('setTimeOutFlag',false);
      //如果当前登录用户不是系统记录用户，则清理菜单和按钮
      if(getStore({name: 'userInfo'}) != null && getStore({name: 'userInfo'}).userName != null){
        if(this.loginForm.username.trim() != getStore({name: 'userInfo'}).userName.trim()){
          removeStore({name: 'menu1'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'menu2'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'menu3'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'menu4'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'menu5'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'menu6'+getStore({name: 'userInfo'}).userId });
          removeStore({name: 'permission'+getStore({name: 'userInfo'}).userId});
        }
      }
      this.$refs.loginForm.validate(valid => {
        //保存登录用户
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '登录中,请稍后。。。',
            spinner: 'el-icon-loading'
          });
          this.reqParams = {
            //chainnelId: 'PC',
            username: this.tenantId+'=user=password=pc=' + this.loginForm.username+'@@password',
            //username: 'pwd='+this.tenantId+'='+this.loginForm.username,
            password: this.$toolUtil.encodeMd5(this.loginForm.password),
            tenantId: this.tenantId
          } 
          
          this.$store.dispatch('LoginByUsername', this.reqParams).then((data) => {
            localStorage.setItem('tenantId', data.additionalInformation.userInfo.tenantId);
            //获取租户及用户设置 
            let singleBody ={
              id: data.additionalInformation.userInfo.userId,
              tenantId: data.additionalInformation.userInfo.tenantId,
              userName: data.additionalInformation.userInfo.userName,
              realName: data.additionalInformation.userInfo.realName
            }  
            this.reqParams =  {
              singleBody: singleBody
            }
            this.commonData = reqCommonMsg(this.reqParams)
            querySysTenantUserSetting(this.commonData).then(res => {
              let newData = res.data.body.singleBody;
              // 对比远程和本地的差异 systemSetting
              let systemSetting = this.$getStore({name: data.additionalInformation.userInfo.userId+'systemSetting'})
              let menuChanged = false;
              let topMenuChanged = false;
              let systemChanged = false;
              let resetChange = false;
              // 判断是否发生改变
              if(systemSetting){
                if(newData.topMenuVersionNo > systemSetting.topMenuVersionNo){
                  topMenuChanged = true;
                }
                if(newData.menuVersionNo > systemSetting.menuVersionNo){
                  menuChanged = true;
                }
                if(newData.systemVersionNo > systemSetting.systemVersionNo){
                  systemChanged = true;
                }
                if(newData.resetNo > systemSetting.resetNo){
                  resetChange = true;
                }
              }
              else{
                topMenuChanged = true;
                menuChanged = true;
                //resetChange = true;
              }
              // 如果重置
              if(resetChange){
                topMenuChanged = true;
                menuChanged = true;
                this.$clearStore();
              }
              //显示通知
              if(systemSetting && newData.msgNo > systemSetting.msgNo){
                const h = this.$createElement;
                this.$notify({
                  title: '通知',
                  message: h('i', { style: 'color: teal'}, newData.noticeMsg),
                  duration: 0,
                  onClose: ()=>{
                  }
                });
              }
              //保存快捷菜单数据
              if(newData.selfDefMenuContent){
                this.$setStore({name: this.userInfo.userId +'QuickMenu', content: JSON.parse(newData.selfDefMenuContent)});
              }
              if(newData.selfDefNaviContent){
                this.$setStore({name: this.userInfo.userId +'selfNaviMenu', content: JSON.parse(newData.selfDefNaviContent)});
              }
              newData.selfDefMenuContent = '';
              newData.selfDefNaviContent = '';
              this.$setStore({name:data.additionalInformation.userInfo.userId+'systemSetting', content: newData});
              localStorage.setItem('tenantId', data.additionalInformation.userInfo.tenantId);
              this.$store.dispatch('setRecordChanged',{
                isMenuChanged: menuChanged,
                isTopMenuChanged: topMenuChanged
              });
              if(newData.validFlag == '1'){
                //登录埋点
                buryingPoint('登录成功','login');
                this.$setStore({name: this.userInfo.userId+'activeIndex',content:'1',type:'session'})
                this.$router.push({path: this.tagWel.value});
              }
              else{
                //登录埋点
                buryingPoint('用户已被禁用','login');
                this.$message({
                  customClass:'zZindex',
                  type: 'error',
                  message: '用户已被禁用!'
                });
                this.$store.dispatch('LogOut').then(() => {
                  this.$router.push({ path: '/index?tenantId='+localStorage.getItem('tenantId')+'&v1'});
                });
              }
              this.$setStore({name:'loginUserName', content:this.loginForm.username, type: ''});
              loading.close();
            }, error => {
              //登录埋点
              buryingPoint('获取用户失败','login');
              loading.close();
              this.settingForm = {};
            });  
          }).catch(() => {
            //登录埋点
            buryingPoint('用户登录失败','login');
            loading.close()
          });
        }
      });
    },
   
  }
};
</script>

<style>
.login-form .el-form-item{
  margin-bottom: 30px !important;
}
</style>
